package com.gardenguell.salad.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.PopupMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.gardenguell.salad.R;
import com.gardenguell.salad.app.AppConstant;
import com.gardenguell.salad.app.HandlerCenter;
import com.gardenguell.salad.data.client.SaladClient;
import com.gardenguell.salad.data.model.Box;
import com.gardenguell.salad.data.volley.OnErrorResponse;
import com.gardenguell.salad.data.volley.OnSuccessResponse;
import com.gardenguell.salad.task.CheckUnitStatusTask;
import com.gardenguell.salad.ui.activity.base.ToolbarActivity;
import com.gardenguell.salad.ui.fragment.MainFragment;
import com.gardenguell.salad.ui.view.MaterialDialog;
import com.gardenguell.salad.util.ResUtil;
import com.gardenguell.salad.util.SharedPreferenceUtil;

public class MainActivity extends ToolbarActivity {

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;

    private FragmentManager mFragmentManager = getSupportFragmentManager();

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case HandlerCenter.Message.TO_BOX_ACTIVITY:
                    Box box = (Box)msg.obj;
                    Intent intent = new Intent(MainActivity.this, BoxActivity.class);
                    intent.putExtra("box", box);
                    startActivity(intent);
                    break;
                case HandlerCenter.Message.ADD_NEW_BOX:
                    // refresh the box list
                    SaladClient client = new SaladClient();
                    String mac = (String)msg.obj;
                    client.addBox(mac, getUsername(), new OnSuccessResponse() {
                        @Override
                        public void onSuccessWithNoBody() {
                            super.onSuccessWithNoBody();
                            Toast.makeText(MainActivity.this, "add box successfully", Toast.LENGTH_SHORT).show();
                            HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.MAIN_FRAGMENT)
                                    .sendEmptyMessage(HandlerCenter.Message.REFRESH_BOX_LIST);
                        }
                    }, MainActivity.this);
                    break;
                case HandlerCenter.Message.CONFIG_WIFI:
                    // refresh the box list
                    Toast.makeText(MainActivity.this, "config wifi success", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public boolean canBack() {
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HandlerCenter.getInstance().setHandler(HandlerCenter.Flag.MAIN_ACTIVITY, mHandler);

        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
        mDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mFragmentManager.beginTransaction()
                .add(R.id.content_fragment, new MainFragment())
                .commit();
        mToolbar.setBackgroundColor(ResUtil.getColor(R.color.main_background));
        setToolbarTitle(ResUtil.getString(R.string.title_activity_main));


        new CheckUnitStatusTask(this).execute();


    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch(v.getId()){
            case R.id.avatar:
                startActivity(new Intent(MainActivity.this, UserInfoActivity.class));
                break;
            case R.id.drawer:
                break;
            default:
                break;
        }
    }

    private void showPopupMemu(View anchor){
        PopupMenu popupMenu = new PopupMenu(this, anchor);
        popupMenu.getMenuInflater().inflate(R.menu.menu_add_config, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                final Intent intent = new Intent(MainActivity.this, ConfigActivity.class);
                SaladClient client = new SaladClient();
                String mac = "001fa88058cf";
                String username = getUsername();
                switch (item.getItemId()){
                    case R.id.add_box:
                        intent.addFlags(ConfigActivity.ADD_BOX);
                        startActivity(intent);
                        /**
                        client.addBox(mac, username, new OnSuccessResponse() {
                            @Override
                            public void onSuccessWithNoBody() {
                                super.onSuccessWithNoBody();
                                Toast.makeText(MainActivity.this, "add box successfully", Toast.LENGTH_SHORT).show();
                                HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.MAIN_FRAGMENT)
                                        .sendEmptyMessage(HandlerCenter.Message.REFRESH_BOX_LIST);
                            }
                        }, MainActivity.this);
                         **/
                        break;
                    case R.id.config_wifi:
                        final MaterialDialog alert = new MaterialDialog(MainActivity.this);
                        alert.setMessage(ResUtil.getString(R.string.config_wifi_tip))
                                .setPositiveButton(R.string.ok, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        // get the module info and config the server infos successfully
                                        intent.addFlags(ConfigActivity.CONFIG_WIFI);
                                        startActivity(intent);
                                        alert.dismiss();
                                    }
                                });
                        alert.setCanceledOnTouchOutside(true);
                        alert.show();
                        /**
                        client.removeBox(mac, username, new OnSuccessResponse() {
                            @Override
                            public void onSuccessWithNoBody() {
                                super.onSuccessWithNoBody();
                                Toast.makeText(MainActivity.this, "remove box successfully", Toast.LENGTH_SHORT).show();
                                HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.MAIN_FRAGMENT)
                                        .sendEmptyMessage(HandlerCenter.Message.REFRESH_BOX_LIST);
                            }
                        }, MainActivity.this);
                         **/
                        break;
                }
                return true;
            }
        });
        popupMenu.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch(itemId){
            case R.id.action_add_config:
                showPopupMemu(findViewById(itemId));
                break;
            default:
                break;
        }
        return true;
    }


    @Override
    public void onBackPressed() {
        if(mFragmentManager.getBackStackEntryCount() == 0){
            super.onBackPressed();
        }else{
            mFragmentManager.popBackStack();
        }
    }

}
